import json
from pathlib import Path


class InputFile(object):
    def __init__(self, data_path: Path, db_file: Path):
        self.data_path = data_path
        self.db_file = db_file
        self.dicts = self.read_file()

    def read_file(self):
        print('*' * 20, 'start reading to file', '*' * 20)
        dicts = []
        roots = [x for x in self.data_path.iterdir() if x.is_dir()]
        for root in roots:
            file_path = self.data_path / root / 'file.txt'
            if not file_path.exists():
                continue
            with open(file_path, encoding='utf-8') as f:
                for line in f:
                    line = line.strip('\n')
                    data = line.split(maxsplit=1)
                    dicts.append({
                        'root': str(root),
                        'file_name': data[0],
                        'file_txt': data[-1],
                        'read_flag': False
                    })
        with open(self.db_file, 'w') as f:
            json.dump(dicts, f)

        return dicts


class OutputFile(object):
    def __init__(self, data_path: Path, file_name: str, db_file: Path):
        self.data_path = data_path
        self.file_name = file_name
        self.db_file = db_file
        self.write_to_file()

    def write_to_file(self):
        print('*'*20, 'start writing to file', '*'*20)
        temp = {}
        with open(self.db_file, 'r') as f:
            dicts = json.load(f)

        for r in dicts:
            line = r['file_name'] + '   ' + r['file_txt'] + '\n'
            if temp.get(r['root']):
                temp[r['root']].append(line)
            else:
                temp[r['root']] = [line]
        print(temp)
        for key in temp:
            file_path = self.data_path / key / self.file_name
            file_data = ''.join(temp[key])
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(file_data)


if __name__ == '__main__':
    # inp = InputFile(data_path='../data')
    # print(inp.dicts)
    #print('*' * 20, 'all file have been read to db', '*' * 20)

    oup = OutputFile(data_path='../data', file_name='file_new.txt')
    print('*'*20, 'writen to file', '*'*20)
